//
//  Game.m
//  genePool_8.2
//
//  Created by Greg Dunn on 11/9/09.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "SSGame.h"

//custom
#import "WolfEntityView.h"
#import "SheepEntityView.h"
#import "WeaponEntityView.h"

#import "SSEntityController.h"

#import "GameSoundManager.h"

#define weaponIntermissionLimit 50

@implementation SSGame


int weaponIntermission = 20;

#pragma mark Custom Methods

- (void) loadLevel:(NSArray *) level
{	
	CMLog(@"loadLevel...");
	
	//[self scheduleUpdate];  // available since v0.99.3
	[self schedule: @selector(update:) interval:1/60.f];
	[self schedule: @selector(enemyUpdate:) interval:7.0f];
	
	rope = [[CCSprite alloc] initWithFile:@"15.png"];
	rope.position = ccp(360, 140);
	[self addChild:rope];
	
	
	//sheep = [[SheepSprite alloc] initWithFile:@"xi_she1.png"];
//	sheep.position = ccp(370, 150);
//	[sheep addPlattform];
//	[self addChild:sheep];
//	
//	laSheep = [[SheepSprite alloc] initWithFile:@"mei_fang1.png"];
//	laSheep.position = ccp(400, 248);
//	[self addChild:laSheep];
//	
//	laSheep2 = [[SheepSprite alloc] initWithFile:@"mei_la1.png"];
//	laSheep2.position = ccp(450, 249);
//	[self addChild:laSheep2];
//	
//	monsters = [[NSMutableArray alloc] init];
	//escapedMonsters = [[NSMutableArray alloc] init];
}

-(void)onEnter{
	[super onEnter];
	
	 self.monsterHit = NO;
}

- (void) startLevel{
	[super startLevel];
}

-(void) checkPlayDie{
	CMLog(@"check play Die...");
	
	NSMutableArray *weaponsToDelete = [[NSMutableArray alloc] init];
	for (CCSprite *weapon in monsterProjectiles) {
		//NSMutableArray *enemysToDelete = [[NSMutableArray alloc] init];
		BOOL hitPlayer = NO;
		CMLog(@"weapon distance: %f", ccpDistance(weapon.position, playerView.position));
		if (ccpDistance(weapon.position, playerView.position) <= 30) {
		//	[enemyController.entityModel.stats setHealth:enemyController.entityModel.stats.health - 1];
		//	CMLog(@"enmey health: %d", enemyController.entityModel.stats.health);
		//	if (enemyController.entityModel.stats.health <= 0) {
		//		[enemysToDelete addObject:enemyController];	
		//	}
			hitPlayer = YES;
			if ([SSStorage getSound]) {
				[soundEngine playEffect:player.entityModel.hitEffectSound pitch:1.0f pan:0.0f gain:player.entityModel.hitEffectGain];
			}
			[player onHit];
			
		}

		
	//	for (SSEntityController *enemyController in enemysToDelete) {
	//		[monsters removeObject:enemyController];
	//		[enemyController.entityView downAndDeathWithDuration:1.0f fallDuration:(enemyController.entityView.position.y - 50)/100.0f endPosition:ccp(00, -enemyController.entityView.position.y +50)];							
	//	}
		
		//if (enemysToDelete.count > 0 || [weapon numberOfRunningActions] == 0) {
		if (hitPlayer){
			[weaponsToDelete addObject:weapon];
		}
		//[enemysToDelete release];
	}
	
	for (CCSprite *weapon in weaponsToDelete) {
		CMLog(@"remove enemyweapon: %@", weapon);
		[weapon stopAllActions];
		
		//[weapon removeFromParentAndCleanup:YES];
		[weapon.parent removeChild:weapon cleanup:YES];
		
		[monsterProjectiles removeObject:weapon];
//		[self removeChild:weapon cleanup:YES];
	}
	[weaponsToDelete release];
	
	if ([player isDead]) {
		[self onGameOver];
	}
}

-(void) checkDelete: (ccTime) dt
{
	CMLog(@"checkDelect...playerProjectiles: %d", [playerProjectiles count]);
	//CMLog(@"checkDelete, playerProjectiles: %d, monsters: %d", [playerProjectiles count], [monsters count]);
	id ropeScale = [CCScaleBy actionWithDuration:2 scaleX:0 scaleY:10];
	[rope runAction:ropeScale];
	
	NSMutableArray *playerProjectilesToDelete = [[NSMutableArray alloc] init];
	for (CCSprite *playerProjectile in playerProjectiles) {
		CMLog(@"next....%d", [playerProjectiles count]);
		NSMutableArray *enemysToDelete = [[NSMutableArray alloc] init];
		for (SSEntityController *monster in monsters) {
			if (ccpDistance(playerProjectile.position, monster.entityView.position) <= 30) {
				//[enemyController.entityModel.stats setHp:enemyController.entityModel.stats.hp - 1]; //TODO
				monster.entityModel.stats.hp--;
				self.monsterHit = YES;
				CMLog(@"now hp: %d", monster.entityModel.stats.hp);
				if (monster.entityModel.stats.hp <= 0) {
					[enemysToDelete addObject:monster];
					
					if ([SSStorage getSound]) {
						[soundEngine playEffect:monster.entityModel.deadEffectSound pitch:1.0f pan:0.0f gain:monster.entityModel.deadEffectGain];
					}
				}else {
					if ([SSStorage getSound]) {
						[soundEngine playEffect:monster.entityModel.hitEffectSound pitch:1.0f pan:0.0f gain:monster.entityModel.hitEffectGain];
					}
				}

				[playerProjectilesToDelete addObject:playerProjectile];
				break;
			}
		}
		
		for (SSEntityController *enemyController in enemysToDelete) {
			[monsters removeObject:enemyController];
			[enemyController.entityView downAndDeathWithDuration:1.0f fallDuration:(enemyController.entityView.position.y - 50)/100.0f endPosition:ccp(00, -enemyController.entityView.position.y +50)];							
		}
		
	//	if (enemysToDelete.count > 0){//|| [weapon numberOfRunningActions] == 0) {
//			[weaponsToDelete addObject:weapon];
//		}
		[enemysToDelete release];
	}
	
	for (CCSprite *playerProjectile in playerProjectilesToDelete) {
		CMLog(@"remove......playerProjectile!!!!");
		[playerProjectiles removeObject:playerProjectile];
		[self removeChild:playerProjectile cleanup:YES];
	}
	[playerProjectilesToDelete release];
	CMLog(@"end check...: %d", [playerProjectiles count]);
	
	[self checkPlayDie];
}

-(void)spawnPlayer{
	CMLog(@"spawn Player");
	
	player = [[SSEntityController alloc]init];
	[[[player entityModel] mobility] setFriction:[currentLevel worldFriction]];
	[[[player entityModel] mobility] setGravity:[currentLevel worldGravity]];
	
	// Animation using Sprite Sheet
	playerView = [[SheepEntityView alloc] init];
	[playerView setController:player];
	[((SheepEntityView *)playerView) addPlattform];
	[player setEntityView:playerView];
	
	[[[player entityModel] stats] setHp:3];
	[[[player entityModel] stats] setMaxHp:3];
	[[player entityModel] setPointPosition:RIGHT];
	[[player entityModel] setShootEffectGain:1.0f];
	[[player entityModel] setShootEffectSound:@"shoot_arrow.wav"];
	
	[playerView setPosition:[currentLevel playerInitialLocation]];
	[playerView setAnchorPoint: ccp(0.5f,0.5f)];
	
    [gameFieldLayer addChild:playerView z:3 tag:0];	
}


-(void) spawnEnemies:(ccTime)dt
{
	CMLog(@"currentLevel_enemies count : %d", [currentLevel.enemies count]);
	if ([currentLevel.enemies count] == 0) {
		CMLog(@"enemies is empty");
		[self unschedule: @selector(spawnEnemies:)];
		return;
	}
	
	
//	EnemyEntityView *enemy = [[currentLevel.enemies objectAtIndex:0] retain];
	SSEntityController *enemyController = [[currentLevel.enemies objectAtIndex:0] retain];
	
	CMLog(@"new enemyController : %@", enemyController);
	//   // WolfEntityView *wolf = [[WolfEntityView alloc] initWithBalloonColor:@"yellow"];
	//	//	[wolf setColor: ccRED];
	enemyController.entityView.position = ccp(10, 290);

	[gameFieldLayer addChild:enemyController.entityView];

	[currentLevel.enemies removeObjectAtIndex:0];

	[monsters addObject:enemyController];

	CMLog(@"7new enemyController : %@", enemyController);
	[((SSEntityView *)enemyController.entityView) run:self];
	CMLog(@"8new enemyController : %@", enemyController);
}

-(void)fire:(ccTime)dt{
	
	//CMLog(@"rightButton.active: %d", [self.rightButton active]);
	if ([self.rightButton active] == YES && weaponIntermission > weaponIntermissionLimit){
		CMLog(@"startWeapon...");
		playerView.color = ccc3(255, 0, 0);
		WeaponEntityView *weapon = [[WeaponEntityView alloc] init];
		weapon.position = ccp(playerView.position.x - 50, playerView.position.y);
		[self addChild:weapon];
		[weapon fireArrow];
		
		[playerProjectiles addObject:weapon];
		weaponIntermission = 0;
		
		if ([SSStorage getSound]) {
			[soundEngine playEffect:player.entityModel.shootEffectSound pitch:1.0f pan:0.0f gain:player.entityModel.shootEffectGain];
		}
	}else {
		playerView.color = ccc3(255,255,255);
		weaponIntermission ++;
	}
	
}


@end
